# coding=utf-8
import xbmc,xbmcaddon,xbmcplugin,xbmcgui,sys,urllib,urllib2,re,os,json,base64
addon_handle = int(sys.argv[1])
xbmcplugin.setContent(addon_handle, 'movies')
#xbmc.executebuiltin('XBMC.RunPlugin(plugin://plugin.video.f4mTester/?url=http%3A%2F%2Fzaphod-live.bbc.co.uk.edgesuite.net%2Fhds-live%2Flivepkgr%2F_definst_%2Fbbc1%2Fbbc1_1500.f4m%7CX-Forwarded-For%3D212.58.241.131)&name=BBC')

def parameters_string_to_dict(parameters):
    ''' Convert parameters encoded in a URL to a dict. '''
    paramDict = {}
    if parameters:
        paramPairs = parameters[1:].split("&")
        for paramsPair in paramPairs:
            paramSplits = paramsPair.split('=')
            if (len(paramSplits)) == 2:
                paramDict[paramSplits[0]] = paramSplits[1]
    return paramDict

def GetUrl(url):
    link = ''
    file = urllib2.urlopen(url)
    link = file.read()
    file.close()
    link = ''.join(link.splitlines()).replace('\'','"')
    link = link.replace('\n','')
    link = link.replace('\t','')
    #link = re.sub('  +',' ',link)
    link = link.replace('> <','><')
    return link

def getHTVChannels ():
    url = "http://api.htvonline.com.vn/tv_channels"
    requestData = '{"pageCount":200,"category_id":"-1","startIndex":0}'
    
    urlRequest = urllib2.Request(urllib.unquote_plus(url))
    urlRequest.add_header ('Content-Type', 'application/x-www-form-urlencoded')
    urlRequest.add_header ('Authorization', 'Basic YXBpaGF5aGF5dHY6NDUlJDY2N0Bk')
    urlRequest.add_header ('User-Agent', 'Apache-HttpClient/UNAVAILABLE (java 1.4)')
    encodeUrlRequest = urllib.urlencode({'request':requestData})
    htmlResponse = urllib2.urlopen(urlRequest, encodeUrlRequest, 120)
    htmlPage = htmlResponse.read()
    htmlResponse.close ()
    htmlPage = ''.join(htmlPage.splitlines())
    result = json.loads(htmlPage)
    return result

def indexHTVChannels(channels):
    for channel in channels["data"]:
        channelName = ''.join(channel ["name"])
        channelResolution = ''.join(channel [ "link_play" ] [ 0 ] [ "resolution" ])
        channelLink = ''.join(channel [ "link_play" ] [ 0 ] [ "mp3u8_link" ])
        strLen = len(channelLink)
        channelLink = channelLink[0:strLen-1]
        channelIcon = ''.join(channel["image"])
        buildLink = sys.argv[0]+'?mode=play'+'&url='+urllib.quote_plus(channelLink)+'&name='+channelName
        li = xbmcgui.ListItem('VN - '+channelName+' '+channelResolution, iconImage=channelIcon)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=buildLink, listitem=li)

def getHTVFoxSport(url, delimiter):
    link = ''
    file = urllib2.urlopen(url)
    link = file.read()
    file.close()
    result = ''.join(re.compile(delimiter).findall(link))
    return result

#================= cookie String in form of cookie.nam=cookie.value;=======================
def getCookiesString(cookieJar):
    try:
        cookieString=""
        for index, cookie in enumerate(cookieJar):
            cookieString+=cookie.name + "=" + cookie.value +";"
    except: pass
    #print 'cookieString',cookieString
    return cookieString

#================If COOKIEFILE is None, create a new cookieJar, otherwise load cookieJar================
def getCookieJar(COOKIEFILE):
    import cookielib
    cookieJar=None
    if COOKIEFILE:
	try:
	    complete_path=os.path.join(profile,COOKIEFILE)
	    cookieJar = cookielib.LWPCookieJar()
	    cookieJar.load(complete_path,ignore_discard=True)
	except: 
	    cookieJar=None
	
    if not cookieJar:
	cookieJar = cookielib.LWPCookieJar()
	
    return cookieJar

def getLocalFoxNews(url):
    #link = getHTVFoxSport(url, delimiter)
    delimiter = '\"m3u8_url\":\"(.+?)\"'
    COOKIEFILE = None
    cookieJar = getCookieJar(COOKIEFILE)
    #print 'cookieJar = ', cookieJar
    #print
    #url = 'http://new.livestream.com/kdfw/live'
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53')
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    opener = urllib2.install_opener(opener)
    response = urllib2.urlopen(req)
    link = response.read()
    response.close()
    reg = re.compile(delimiter).search(link)
    val=reg.group(1).strip()
    #print 'val = ', val
    #print
    req = urllib2.Request(val)
    req.add_header('User-Agent', 'AppleCoreMedia/1.0.0.11B554a (iPhone; U; CPU OS 7_0_4 like Mac OS X; en_gb)')
    #req.add_header('User-Agent', 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53')
    cookie_handler = urllib2.HTTPCookieProcessor(cookieJar)
    opener = urllib2.build_opener(cookie_handler, urllib2.HTTPBasicAuthHandler(), urllib2.HTTPHandler())
    opener = urllib2.install_opener(opener)
    response = urllib2.urlopen(req)
    link = response.read()
    response.close()
    import uuid
    guid = str(uuid.uuid1()).upper()
    final_url = val+'|Cookie='+getCookiesString (cookieJar)+'&User-Agent=AppleCoreMedia/1.0.0.11B554a (iPhone; U; CPU OS 7_0_4 like Mac OS X; en_gb)&X-Playback-Session-Id='+guid
    #print final_url
    return final_url
    
def getCookiesString(cookieJar):
    try:
        cookieString=""
        for index, cookie in enumerate(cookieJar):
            cookieString+=cookie.name + "=" + cookie.value +";"
    except: pass
    print 'cookieString',cookieString
    return cookieString

def Index(groupURL):
    if groupURL.startswith('getHTVChannels'):
        indexHTVChannels(getHTVChannels())
        
    else:
        link = urllib.unquote_plus(groupURL)
        buildStr=''
        xmlcontent = GetUrl(link)
        channels = re.compile('<channel>(.+?)</channel>').findall(xmlcontent)
        
        for channel in channels:
            channelName = ''.join(re.compile('<name>(.+?)</name>').findall(channel))
            channelLink = ''.join(re.compile('<link>(.+?)</link>').findall(channel))
            channelPlayPath = ''.join(re.compile('<playpath>(.+?)</playpath>').findall(channel))
            channelToken = ''.join(re.compile('<token>(.+?)</token>').findall(channel))
            channelSwfURL = ''.join(re.compile('<swfURL>(.+?)</swfURL>').findall(channel))
            channelPageURL = ''.join(re.compile('<pageURL>(.+?)</pageURL>').findall(channel))
            channelThumbnail = ''.join(re.compile('<thumbnail>(.+?)</thumbnail>').findall(channel))
            if channelLink.startswith('http:') or channelLink.startswith('https:') or channelLink.startswith('rtsp:') or channelLink.startswith('mms:'):
                buildStr = channelLink
            elif channelLink.startswith('getHTVFoxSport'):
                buildStr = channelLink
            else:
                buildStr = channelLink
                if channelPlayPath !='':
                    buildStr = buildStr+' playpath='+ channelPlayPath
                if channelToken !='':
                    buildStr = buildStr+' token='+channelToken
                if channelSwfURL !='':
                    buildStr = buildStr+' swfURL='+channelSwfURL
                if channelPageURL !='':
                    buildStr = buildStr+' pageURL='+channelPageURL
                buildStr = buildStr +' live=1 timeout=45'
                
            buildStr = sys.argv[0]+'?mode=play'+'&url='+urllib.quote_plus(buildStr)+'&name='+urllib.quote_plus(channelName)
            li = xbmcgui.ListItem(channelName, iconImage=channelThumbnail)
            xbmcplugin.addDirectoryItem(handle=addon_handle, url=buildStr, listitem=li)
    xbmc.executebuiltin("Container.SetViewMode(50)")
    
def Home():
    xmlcontent = GetUrl('http://magicbox-vip-playlist.googlecode.com/svn/trunk/source_file.xml')
    channels = re.compile('<channel>(.+?)</channel>').findall(xmlcontent)
    
    for channel in channels:
        chName = ''.join(re.compile('<name>(.+?)</name>').findall(channel))
        chLink = ''.join(re.compile('<link>(.+?)</link>').findall(channel))
        url = sys.argv[0]+'?mode=index'+'&groupURL='+chLink
        li = xbmcgui.ListItem(chName, iconImage='icon.png')
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    xbmc.executebuiltin("Container.SetViewMode(50)")
        
def PlayStream(streamURL, streamName):
    link = urllib.unquote_plus(streamURL)
    name = urllib.unquote_plus(streamName)
    if '.f4m' in link:
        encodedURL = 'plugin://plugin.video.f4mTester/?url='+streamURL
        xbmc.executebuiltin('XBMC.RunPlugin(plugin://plugin.video.f4mTester/?url='+streamURL+')')
        """from F4mProxy import f4mProxyHelper
        player=f4mProxyHelper()
        player.playF4mLink(link, name,use_proxy_for_chunks=False, maxbitrate=-1)"""
    elif 'youtube' in link: 
        videoID=link.split('https://www.youtube.com/watch?v=')
        url = 'plugin://plugin.video.youtube?path=/root/video&action=play_video&videoid='+videoID[1]
        xbmc.executebuiltin("xbmc.PlayMedia("+url+")")
    elif 'getHTVFoxSport' in link:
        link = getHTVFoxSport('http://www.htvonline.com.vn/livetv/espn-hd-3132346E61.html', 'file: \"(.+?)\",')
        li = xbmcgui.ListItem(name)
        xbmc.Player().play(item=link, listitem=li)
    elif 'getLocalFoxNews' in link:
        #print 'link:', link
        reg = re.compile('"(.+?)"').search(link)
        #print reg
        url=reg.group(1).strip()
        link = getLocalFoxNews(url)
        li = xbmcgui.ListItem(name)
        xbmc.Player().play(item=link, listitem=li)
    else:
        li = xbmcgui.ListItem(name)
        xbmc.Player().play(item=link, listitem=li)
    
params = parameters_string_to_dict(sys.argv[2])
mode=params.get('mode')

if mode=='index':
    groupURL=params.get('groupURL') 
    Index(groupURL)
elif mode=='play':
    streamURL=params.get('url')
    streamName=params.get('name')
    dialogWait = xbmcgui.DialogProgress()
    dialogWait.create('Brought to you by Magic Box', 'Loading video. Please wait...')
    PlayStream(streamURL, streamName)
    dialogWait.close()
    del dialogWait
else:
    Home()
xbmcplugin.endOfDirectory(addon_handle)

